package com.cx.common.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IllegalStrFilterUtil {

	private static final Log logger = LogFactory.getLog(IllegalStrFilterUtil.class);

	private static final String REGX = "！|@|◎|#|＃|(\\$)|￥|%|％|(\\^)|……|(\\&)|※|(\\*)|×|(\\()|（|(\\))|）|——|(\\|)|§ ";

	private static final String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|%|chr|mid|master|truncate|"
			+ "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|"
			+ "table|from|grant|use|group_concat|column_name|information_schema.columns|table_schema|"
			+ "union|where|select|delete|update|count|chr|mid|truncate|char|declare|or|;|-|--|,|like|//|/|%|#";

	/**
	 * 
	 * @Description: true 表示参数不存在SQL注入风险 false 表示参数存在SQL注入风险
	 * @title: checkSqlStrFilter
	 * @Author:cxy
	 * @Date:2019/10/24 15:11
	 * @param value
	 * @return
	 * @return: Boolean
	 */
	public static Boolean checkSqlStrFilter(String value) {
		if (value == null || value.trim().length() == 0) {
			return true;
		}
		value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
		value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
		value = value.replaceAll("'", "& #39;");
		value = value.replaceAll("eval\\((.*)\\)", "");
		value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
		value = value.replaceAll("script", "");
		value = value.replaceAll(";", " ");
		String[] values = value.split(" ");
		String[] badStrs = badStr.split("\\|");
		for (int i = 0; i < badStrs.length; i++) {
			for (int j = 0; j < values.length; j++) {
				if (StringUtils.isNotBlank(values[j]) && values[j].equalsIgnoreCase(badStrs[i])) {
					logger.error("param SQL injection : value=" + values[j]);
					return false;
				}
			}
		}
		logger.debug("通过sql检测" + value);
		return true;
	}

	/**
	 * 对非法字符进行检测
	 * 
	 * @param sInput
	 * @return true 表示参数不包含非法字符 false 表示参数包含非法字符
	 */
	public static boolean checkIllegalStr(String sInput) {
		if (sInput == null || sInput.trim().length() == 0) {
			return true;
		}
		sInput = sInput.trim();
		Pattern compile = Pattern.compile(REGX, Pattern.CASE_INSENSITIVE);
		Matcher matcher = compile.matcher(sInput);
		logger.info("通过字符串检测");
		return !matcher.find();
	}

}
